package com.iemp.advice;

import com.iemp.exception.AbstractStateExceptionHandler;
import com.iemp.exception.entity.base.AbstractStateException;
import com.iemp.my.CustomString;
import com.iemp.result.JsonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collection;

@RestControllerAdvice(basePackages = "com.iemp.web.controller.file")
public class FileTransferResponseAdvice implements ResponseBodyAdvice<Object>, AbstractStateExceptionHandler {
    @Override
    public AbstractStateException exceptionWithState(AbstractStateException exception) {
        return exception;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        /* todo ResponseBody instanceof [Interface] ? */

        if (body instanceof HttpEntity) {
            return body;
        }
        if (body instanceof Collection) {
            return JsonResult.create(body);
        }
        if (body instanceof CustomString) {
            return JsonResult.create(body.toString());
        }
        if (body instanceof AbstractStateException) {
            return JsonResult.create((AbstractStateException) body);
        }
        return body;
    }
}
